'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {

    async register() {
        const {service} = this.ctx;
        const data = this.ctx.request.body

        if (!data.name || !data.email || !data.password || !data.confirmPassword || !data.yzCode || !data.scoreLevel) throw {code: '02', msg: '请完整填写必要信息'}

        if (['1', '2', '3'].indexOf(data.scoreLevel) == -1) throw {code: '02', msg: '书龄填写错误'}

        if (data.password != data.confirmPassword) throw {code: '02', msg: '重复密码不一致'}

        if (data.password.length < 6) throw {code: '02', msg: '密码长度太低'}

        const yzCode = await service.redis.get(data.email);
        // console.log(yzCode)
        if (data.yzCode != yzCode) throw {code: '02', msg: '验证码错误'}

        const params = {
            name: data.name,
            email: data.email,
            password: data.password,
            confirmPassword: data.confirmPassword,
            scoreLevel: Number(data.scoreLevel),
            yzCode: data.yzCode
        }

        let result = await service.user.register(params)

        if (!result[1]) throw {code: '02', msg: '该邮箱已注册或昵称重复'}

        const token = this.app.jwt.sign({
            userId: result[0].id,	//需要存储的Token数据
        }, this.app.config.jwt.secret, {
            // expiresIn: '60m', // 时间根据自己定，具体可参考jsonwebtoken插件官方说明
        });
        result[0] = JSON.parse(JSON.stringify(result[0]))
        result[0]['token'] = token

        return result
    }

    async signIn() {
        const {service} = this.ctx;
        const data = this.ctx.request.body
        const params = {
            email: data.email,
            password: data.password
        }

        let result = await service.user.signIn(params);

        if (!result) throw {code: '02', msg: '账号或密码有误'}

        result = JSON.parse(JSON.stringify(result))
        const token = this.app.jwt.sign({
            userId: result.id,	//需要存储的Token数据
        }, this.app.config.jwt.secret, {
            // expiresIn: '60m', // 时间根据自己定，具体可参考jsonwebtoken插件官方说明
        });

        result['token'] = token

        return result
    }

    async getInfo() {
        const userId = this.ctx.token.userId
        return await this.app.model.User.findByPk(userId);
    }
}

module.exports = UserController;
